package com.heu.blood.match.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.heu.blood.common.commponent.DictionaryLoader;
import com.heu.blood.common.utils.BeanUtils;

import java.util.Map;

public class DictConverter implements Converter<String> {
    private DictionaryLoader dictionaryLoader;
    Map<String, String> codeMapping;

    public DictConverter(){
        this.dictionaryLoader = BeanUtils.getBean(DictionaryLoader.class);
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadConverterContext<?> context) {
        System.out.println("dictionaryLoader: " + dictionaryLoader);
        if (codeMapping == null) {
            codeMapping = dictionaryLoader.getSubDict();
        }
        String value = context.getReadCellData().getStringValue();
        return codeMapping.getOrDefault(value, value);
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
        return new WriteCellData<>(context.getValue());
    }
}
